define(['../../common/service'], function(http){
    var gaAccountManage = {
        init : function(){
            var _this = this;
            //列表管理
            $('table[list-manager="gaList"]').listManager('init',{
                setTopVal:$('table[list-manager="gaList"]').offset().top//调整吸顶的高度,需要减去这个高度
                ,scrollDOM:$('.fmp-article')//监听滚动条
                ,supportAjaxPage: true
                ,pageCallback:function(query){
                    _this.query = query;
                    _this.getList(query);
                }
            }, function(query){
                _this.query = query;
                _this.getList(query);
            });
            _this.bindEvent();
        },
        bindEvent : function(){
            var _this = this;
            //解绑GA
            var _gaList = $("#gaList");
            _gaList.off("click", ".unbind").on("click", ".unbind", function(){
                var prodId = $(this).parents("tr").data("gaAccount").prodId;
                showConfirm({
                    title:I18N.getText('gaAccountManage','unbindGaAccount'),
                    content:I18N.getText('gaAccountManage','unbindGaReminder'),
                    btnOK: I18N.getText('gaAccountManage','confirm'),//确定按钮文字
                    btnCANCEL: I18N.getText('gaAccountManage','cancel'),//关闭按钮文字
                    onOK:function(){// 点击 “确认” 按钮回调函数
                       var param = {
                           productId: prodId
                       }

                        http.work('/ga/unauth',param,'POST').then(function(res){

                        }).done(function(){
                            _this.getList(_this.query);
                        });
                    },
                    onCancel:function(){// 点击 “取消” 或者x 按钮回调函数
                        console.log("取消");
                    }
                });
            })

            //重试
            _gaList.off("click", ".status-failed").on("click", ".status-failed", function(){
                var _gaAccount = $(this).parents("tr").data("gaAccount");
                var prodId = _gaAccount.prodId;
                var gaUserName = _gaAccount.gaUserName;
                var trackingId = _gaAccount.trackingId;
                var param = {productId:prodId, trackingId:trackingId, gaUserName:gaUserName};
                _this.authR(param)
            })


            _this.bindAuth();

        },
        bindAuth : function(){
            var _this = this;
            //生成选择账号弹出框
            var _gaAuthM = $("#ga-auth");
            _gaAuthM.modal({
                keyboard: false,
                show:false
            });

            //绑定GA
            var _gaList = $("#gaList");
            _gaList.off("click", ".bind").on("click", ".bind",function(){
                var productId = $(this).parents("tr").data("gaAccount").prodId;
                _gaAuthM.find('input[name="ga-account"]').val('');
                _gaAuthM.find('input[name="data-profile-Id"]').val('');
                _gaAuthM.find('input[name="product-id"]').val(productId);
                $(".form-input-warning").removeClass('form-input-warning');
                $(".warning-r").addClass('hide');

                _gaAuthM.modal("show");
            })

            _gaAuthM.off("click", ".auth-btn").on("click", ".auth-btn", function(){
                $(".form-input-warning").removeClass('form-input-warning');
                $(".warning-r").addClass('hide');

                var gaAccountE =  _gaAuthM.find('input[name="ga-account"]');
                var trackingIdE =  _gaAuthM.find('input[name="data-tracking-Id"]');

                var gaAccountV = $.trim(gaAccountE.val());
                var trackingIdV = $.trim(trackingIdE.val());
                //校验
                if (gaAccountV == ''){
                    _this.errorR(gaAccountE, I18N.getText('gaAccountManage','gaAccountHolder'))
                    return false;
                }
                if (trackingIdV == ''){
                    _this.errorR(trackingIdE, I18N.getText('gaAccountManage','trackingIdHolder'))
                    return false;
                }

                var productId = _gaAuthM.find('input[name="product-id"]').val();
                var param = {productId:productId, trackingId:trackingIdV, gaUserName:gaAccountV};
                _this.authR(param, function(){
                    _gaAuthM.modal("hide");
                })

            })
        },
        errorR : function(_e, msg){
            $(_e).addClass('form-input-warning');
            $(_e).next(".warning-r").html(msg).removeClass("hide");
        },
        authR : function(_param, successCallBack){
            http.work('/ga/auth',_param,'POST').then(function(res){
                if (res.flag == 'success'){
                    //console.log(res.data.redirectUri)
                    window.top.location.href = res.data.redirectUri;
                    if (successCallBack){
                        successCallBack();
                    }
                }
            }, function(res){
                console.log(res)
            });
        },
        getList : function(query){
            if (!query.pSize){
                query.pSize = 20;
            }
            var _this = this;
            var loadingArea = $('.fmp-container');
            Kit.loading.show(loadingArea);
            var  _table = $('table[list-manager="gaList"]'),
                _tbody = _table.find("tbody");
            _tbody.empty();
            http.work('/ga/findecgacredential',query,'GET').then(function(res){
                if(res.flag == 'success'){
                    var _list = res.data.ecGaCredentials,
                        _paginator = res.data.paginator,
                        _serial = 0;		//序号
                    for(var i=0; i< _list.length; i++){
                        _serial = (_paginator.cPage-1) * _paginator.pSize +i + 1;
                        _tbody.append(_this.generateHTML(_list[i],_serial));
                    }

                    _table.listManager([{'resetTd':false, 'resetPageData': _paginator}]);
                    $(window).trigger('resize');
                }else{
                    Kit.alert2(res.msg || I18N.getText('gaAccountManage','queryFailed'))
                }

            }).done(function(){
                Kit.loading.hide(loadingArea);
            });
        },
        generateHTML : function(_gaAccount, num){
            var _tr = '<tr>'
                + '<td>' + num + '</td>'
                + '<td>' + _gaAccount.prodName + '</td>'
                + '<td>' + (_gaAccount.gaUserName || '--') + '</td>';
            var _status = '';
            if (!_gaAccount.status || _gaAccount.status == 0 || _gaAccount.status == 3){
                _status = '--';
            } else if (_gaAccount.status == 1){
                //授权成功
                _status = '<span class="font-icon font-icon-check status-success"></span>';
            } else {
                //授权失败 可重试
                _status = '<span class="status-failed"><i class="font-icon font-icon-update icon-btn"></i><span class="btn btn-link icon-text">'
                    + I18N.getText('gaAccountManage','retry') +'</span></span>';
            }

            var _action = '<span class="unbind"><i class="fa fa-unlink icon-btn"></i><span class="btn btn-link icon-text">'
                + I18N.getText('gaAccountManage','unbindGa') + '</span></span>';
            if (!_gaAccount.status || _gaAccount.status == 0 || _gaAccount.status == 3){
                _action = '<span class="bind"><i class="glyphicon glyphicon-cog icon-btn"></i><span class="btn btn-link icon-text">'
                    + I18N.getText('gaAccountManage','bindGa') +'</span></span>';
            }

            //操作时间
            var _updateTime = '';
            if (!_gaAccount.updateTime){
                _updateTime = '--';
            } else{
                var timezoneValue = window.sessionStorage.timezoneValue;
                _updateTime = moment(_gaAccount.updateTime).utcOffset(timezoneValue).format('YYYY-MM-DD HH:mm');
            }

            _tr += '<td>' + _status + '</td>';
            _tr +=
                '<td>' + _action + '</td>'
                + '<td>' + _updateTime + '</td>'
            _tr += '</tr>';

            var _trE = $(_tr);
            _trE.data("gaAccount", _gaAccount);
            return _trE;
        }
    };
    return gaAccountManage;
})
